package logic

import (
	"classtype/classtype"
	"classtype/global/model"
	"classtype/internal/svc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassTypeCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassTypeCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassTypeCreateLogic {
	return &ClassTypeCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassTypeCreateLogic) ClassTypeCreate(in *classtype.ClassTypeCreateRequest) (*classtype.ClassTypeCreateResponse, error) {
	// todo: add your logic here and delete this line
	var ClassType model.ClassTypes
	if err := model.DB.Where("name = ?", in.Name).Find(&ClassType).Error; err != nil {
		return nil, err
	}
	if ClassType.ID != 0 {
		return nil, fmt.Errorf("已存在该分类")
	}
	if in.Sort < 0 {
		return nil, fmt.Errorf("排序值不可为负")
	}
	if in.ParentId < 0 {
		return nil, fmt.Errorf("父id不得为负")
	}
	ClassType = model.ClassTypes{
		Name:        in.Name,
		ParentId:    int32(in.ParentId),
		Description: in.Description,
		Sort:        int32(in.Sort),
	}
	if err := model.DB.Create(&ClassType).Error; err != nil {
		return nil, err
	}
	model.RDB.Del(model.Ctx, "tree")
	return &classtype.ClassTypeCreateResponse{}, nil
}
